use actix_web::{body::BoxBody, http::header::ContentType, HttpResponse, Responder};

use crate::web::cfg::{HTTP_FILE_NAME_HEAD, HTTP_RESP_HEAD, HTTP_RESP_OK};

use super::RawBody;

pub struct Download {
    name: String,
    body: Box<[u8]>,
}

pub fn new_download(name: String, body: Box<[u8]>) -> Download {
    Download { name, body }
}

impl Responder for Download {
    type Body = BoxBody;

    fn respond_to(self, _req: &actix_web::HttpRequest) -> HttpResponse {
        let name = format!("attachment; filename={}", self.name);
        HttpResponse::Ok()
            .content_type(ContentType::octet_stream())
            .insert_header((HTTP_RESP_HEAD, HTTP_RESP_OK))
            .insert_header((HTTP_FILE_NAME_HEAD, name))
            .body(RawBody(self.body))
    }
}
